﻿using System;
using System.Xml;

namespace CSLive.ControlPanel
{
    public struct ConfigSetting
    {
        /// <summary>
        /// Name of the Setting
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// Description of the Setting
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// Value of the Setting as an object
        /// </summary>
        public object Value { get; set; }

        /// <summary>
        /// Parses an XML node and turns it into a ConfigSetting
        /// </summary>
        /// <param name="setting">XmlNode from the CommunityServer.config file for the control setting</param>
        /// <returns>a Config Setting Matching the XML node</returns>
        public static ConfigSetting Parse( XmlNode setting )
        {
            ConfigSetting c = new ConfigSetting();
            try
            {
                Type type = Type.GetType( setting.Attributes[ "type" ].Value );
                c.Description = (setting.Attributes[ "description" ] != null) ? setting.Attributes[ "description" ].Value : setting.SelectSingleNode("description").InnerText;
                c.Name = setting.Attributes[ "name" ].Value;
                if ( type.IsEnum ) c.Value = Enum.Parse( type, setting.Attributes[ "defaultvalue" ].Value );
                else if ( type == typeof ( Html ) ) c.Value = Html.Parse( setting.SelectSingleNode( "defaultvalue" ).InnerText );
                else if ( type == typeof ( Int32 ) ) c.Value = Int32.Parse( setting.Attributes[ "defaultvalue" ].Value );
                else if ( type == typeof ( bool ) ) c.Value = bool.Parse( setting.Attributes[ "defaultvalue" ].Value );
                else c.Value = setting.Attributes[ "defaultvalue" ].Value;
            }
            catch ( Exception e )
            {
                throw new XmlException( "Unable to Find Property", e );
            }
            return c;
        }

        public override string ToString()
        {
            
            return this.Value.ToString();
        }
    }
}